<template>
  <div style="height:100vh">
    <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 100%"
    :height="500"
    @select="select"
    @row-click="rowClick"
    @selection-change="selectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column label="Date" width="120" />
    <el-table-column property="name" label="Name" width="120" />
    <el-table-column property="address" label="Address" show-overflow-tooltip />
  </el-table>
  <div style="margin-top: 20px">
    <el-button @click="setCurrent(tableData[1])">Select second row</el-button>
    <el-button @click="setCurrent()">Clear selection</el-button>
  </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const multipleTableRef = ref()
const multipleSelection = ref([])
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach(row => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const rowClick = () =>{
    const selectData = this.selectData
    multipleTableRef.clearSelection()
    if( selectData.length == 1 ) {
        selectData.forEach(item => {
            // 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
            if (item == row) {
                multipleTableRef.value.toggleRowSelection(row, false);
            }
            // 不然就让当前的一行勾选
            else {
                multipleTableRef.value.toggleRowSelection(row, true);
            }
        })
    } 
    else {
        multipleTableRef.value.toggleRowSelection(row, true);
    }
}

const select = (selection, row)=>{
    // 清除 所有勾选项
    multipleTableRef.value.clearSelection()
    // 当表格数据都没有被勾选的时候 就返回
    // 主要用于将当前勾选的表格状态清除
    if(selection.length == 0) return
    multipleTableRef.value.toggleRowSelection(row, true);
}

const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-08',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-06',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-07',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
]
</script>

<style>

</style>